(function () {
	//默认展开级别初始化
	$.ajax({
		url: "../basedata/query.action",
		type: "post",
		async: false,
		data: {"id" : "20171026000003"},
		success: function(data) {
			//console.log(data);
			$("tree-grid").attr('expand-level',data[0].level2Value);
		},
		error: function() {
			toastr.error("获取树级表格默认展开级别出错，请联系管理员");
		}
	});
	
	
	
	
	
	
    var app, deps;

    deps = ['treeGrid'];

    app = angular.module('treeGridTest', deps);

    app.controller('treeGridController', function ($scope, $timeout) {
        var tree;


        var myTreeData = getTreeData();

        $scope.tree_data = myTreeData;//赋值语句
        $scope.my_tree = tree = {};
        $scope.expanding_property = {
            field: "menuName",
            displayName: "菜单名",
            sortable: true,
            filterable: true,
            cellTemplate: "<i>{{row.branch[expandingProperty.field]}}</i>"
        };
        $scope.col_defs = [
            {
                field: "menuDesc",
				displayName : "菜单描述",
                sortable: true,
                sortingType: "string",
                filterable: true,
                cellTemplate: "<div class='td-cont-3'>{{row.branch.menuDesc}}</div>"
            },
            {
                field: "menuUrl",
                displayName : "访问地址",
                sortable: true,
                sortingType: "string",
                filterable: true
            },
            {
                field: "menuType",
                displayName : "菜单类型",
                filterable: true
            },
            {
                field: "menuOrder",
                displayName : "同级启动排序",
                sortable: true,
                sortingType: "number",
                filterable: true
            },
            {
                field: "operate",
                displayName: "操作",
                //cellTemplate: "<span style='display:none'>{{row.branch.id}}</span><button class='btn btn-primary btn-xs' onclick='update(this)'>修改</button> <button class='btn btn-danger btn-xs' onclick='forbidden()'>禁用</button>"
                cellTemplate: "<div ng-controller=\"OperateController\"><button class=\"btn btn-primary btn-xs\" ng-click=\"update(row.branch)\">修改</button> <button ng-if=\"!isForbidden(row.branch)\" class=\"btn btn-danger btn-xs\" ng-click=\"forbidden(row.branch)\">禁用</button><button ng-if=\"isForbidden(row.branch)\" class=\"btn btn-info btn-xs\" ng-click=\"removeForbidden(row.branch)\">启用</button></div>"
            }
        ];
        $scope.my_tree_handler = function (branch) {
            //console.log('you clicked on', branch)
        	
        }
    });
    
    app.controller('TableRowController', function($scope, $timeout) {
		$scope.tableRowDbClick = function(branch) {
			menuDetail(branch);
		}
    });
    app.controller('OperateController', function($scope,$rootScope) {
    	$scope.isForbidden = function (branch) {
    		if (branch.menuStatus == "0") {
    			return true;
    		}
    		return false;
    	}
    	$scope.update = function (branch) {
        	//console.log(branch);
        	update(branch);
        	//$rootScope.$$childHead.tree_data = getTreeData();//找这个方法找了n年，不熟悉的组件打印出来看一看
        }
    	
    	$scope.forbidden = function (branch) {
    		//console.log("禁用");
    		//console.log(branch);
    		
    		swal({
    	        title: "您确定要禁用所选菜单吗",
    	        text: "请确保该菜单下无子菜单，否则请先禁用其子菜单！",
    	        type: "warning",
    	        async: false,
    	        showCancelButton: true,
    	        confirmButtonColor: "#DD6B55",
    	        confirmButtonText: "禁用",
    	        closeOnConfirm: false
    	    }, function () {
    	    	var isExist = isExistSubMenu(branch.id, "1");
    	    	if (isExist == true) {
    	    		swal("禁用失败", "该菜单下存在子菜单，请先禁用其子菜单", "error");
    	    		return;
    	    	} else if(isExist == "-1") {
    	    		swal("禁用失败", "提交请求发生错误，请联系管理员", "error");
    	    		return;
    	    	}
    	    	$.ajax({
    	    		url: "../menu/update.action",
    	    		type: "post",
    	    		data: {"id":branch.id,"menuStatus":"0"},
    	    		async: false,
    	    		success: function(data) {
    	    			if (data.success == "true") {
    	    				swal("禁用成功", "您已经成功禁用了所选菜单。", "success");
    	    				result = "true";
    	    			} else {
    	    				swal("禁用失败", "后台业务处理发生错误，请联系管理员", "error");
    	    			}
    	    		},
    	    		error: function() {
    	    			swal("操作失败", "提交到数据库发生错误，请联系管理员。", "error");
    	    		}
    	    	});
    	    	console.log(result);
    	    	$rootScope.$$childHead.tree_data = getTreeData();//找这个方法找了n年，不熟悉的组件打印出来看一看
    	    	$rootScope.$apply();
    	    });
    	}
    		
		$scope.removeForbidden = function (branch) {
			//console.log("启用");
			//console.log(branch);
			swal({
				title: "您确定要启用所选菜单吗",
				text: "请确保该菜单下无子菜单，否则请先启用其子菜单！",
				type: "warning",
				async: false,
				showCancelButton: true,
				confirmButtonColor: "#DD6B55",
				confirmButtonText: "启用",
				closeOnConfirm: false
			}, function () {
				var isExist = isExistSubMenu(branch.id, "0");
    	    	if (isExist == true) {
    	    		swal("启用失败", "该菜单下存在子菜单，请先启用其子菜单", "error");
    	    		return;
    	    	} else if(isExist == "-1") {
    	    		swal("启用失败", "提交请求发生错误，请联系管理员", "error");
    	    		return;
    	    	}
				$.ajax({
					url: "../menu/update.action",
					type: "post",
					data: {"id":branch.id,"menuStatus":"1"},
					async: false,
					success: function(data) {
						if (data.success == "true") {
							swal("启用成功", "您已经成功启用了所选菜单。", "success");
						} else {
							swal("启用失败", "后台业务处理发生错误，请联系管理员", "error");
						}
					},
					error: function() {
						swal("操作失败", "提交请求发生错误，请联系管理员。", "error");
					}
				});
				$rootScope.$$childHead.tree_data = getTreeData();//找这个方法找了n年，不熟悉的组件打印出来看一看
				$rootScope.$apply();
			});
		}
    });
    app.controller('UpdateMenuSaveController', function($scope,$rootScope) {
    	$scope.updateMenuSave = function () {
    		console.log("save");
    		
    		updateMenuSave();
    		$rootScope.$$childHead.tree_data = getTreeData();//找这个方法找了n年，不熟悉的组件打印出来看一看
    	}
    });
    
    
}).call(this);

//菜单详情
function menuDetail(menu) {
	var menuDetailHtml = '<p>id：' + menu.id + '</p>'
					+	'<p>菜单名：' + menu.menuName + '</p>'
					+	'<p>菜单描述：' + menu.menuDesc + '</p>'
					+	'<p>菜单类型：' + menu.menuType + '</p>'
					+	'<p>菜单地址：' + menu.menuUrl + '</p>'
					+	'<p>级别：' + menu.menuLevel + '</p>'
					+	'<p>同级排序：' + menu.menuOrder + '</p>';
	
	$("#menuDetailShow").html(menuDetailHtml);
	$("#menuDetailModal").modal("show");
}
function isExistSubMenu(menuId, status) {
	var result = true;
	$.ajax({
		url: "../menu/isExistSubMenu.action",
		type: "post",
		data: {"parentMenuId": menuId, "menuStatus": status},
		async: false,
		success: function(data) {
			if (data == "false") {
				result = false;
			}
		},
		error: function() {
			result = -1;
		}
	});
	return result;
}


function getTreeData() {
	var rawTreeData = '';
    $.ajax({
    	url: "../menu/query.action",
    	type: "post",
    	async: false,
    	success: function(data) {
    		//将数据类型由基本数据表中的id换成名字
    		$(data).each(function(){
    			var menuTypeBasedata = getBasedataById(this.menuType);
    			this.menuType = menuTypeBasedata.level2Name;
    		});
    		rawTreeData = data;
    	},
    	error: function() {
    		toastr.error("获取菜单数据出错，请联系管理员");
    	}
    });
    var data = rawTreeData;
    var primaryIdName = 'id';
    var parentIdName = 'parentMenuId';
    if (!data || data.length == 0 || !primaryIdName || !parentIdName)
        return [];

    var tree = [],
        rootIds = [],
        item = data[0],
        primaryKey = item[primaryIdName],
        treeObjs = {},
        parentId,
        parent,
        len = data.length,
        i = 0;

    while (i < len) {
        item = data[i++];
        primaryKey = item[primaryIdName];
        treeObjs[primaryKey] = item;
        parentId = item[parentIdName];

        if (parentId != -1) {
            parent = treeObjs[parentId];

            if (parent.children) {
                parent.children.push(item);
            } else {
                parent.children = [item];
            }
        } else {
            rootIds.push(primaryKey);
        }
    }

    for (var i = 0; i < rootIds.length; i++) {
        tree.push(treeObjs[rootIds[i]]);
    };

    return tree;
}


function update(menu) {
	//console.log(menu);
	formReset("#updateMenuForm");
	$("#updateMenuForm [name='id']").val(menu.id);
	$("#updateMenuForm [name='menuName']").val(menu.menuName);
	$("#updateMenuForm [name='menuDesc']").text(menu.menuDesc);
	$("#updateMenuModal").modal("show");
}
function updateMenuSave() {
	$.ajax({
		url: "../menu/update.action",
		type: "post",
		async: false,
		data: $("#updateMenuForm").serialize(),
		success: function(data) {
			if (data.success == "true") {
				toastr.success("更新成功");
			}
		},
		error: function() {
			toastr.error("提交到数据库发生错误，请联系管理员");
		}
	});
	$("#updateMenuModal").modal("hide");
}




function updateSort() {
	window.location.href = "../menu/updateSort.action";
}
